package com.caohx.bms.controller;

import com.caohx.bms.pojo.ResponseMessage;
import com.caohx.bms.pojo.User;
import com.caohx.bms.pojo.dto.EmailRequestDto;
import com.caohx.bms.pojo.dto.LoginDto;
import com.caohx.bms.pojo.dto.UserDto;
import com.caohx.bms.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController  //接口返回对象 将转换成json 传给前端
                 //rest风格 将增删改查 请求用 html的 post、delete、put、get
@RequestMapping("/user")  //请求路径    localhost:8666/user
public class UserController {

    @Autowired
    IUserService userService;

    //增加用户
    @PostMapping  //请求方式为post
    public ResponseMessage add(@Validated  @RequestBody UserDto user)
    {
     User user1 =    userService.add(user);
      return ResponseMessage.success(user1);

    }

    //修改用户
    @PutMapping  //请求方式为put
    public ResponseMessage edit(@Validated  @RequestBody UserDto user)
    {
        if (user.getUserID() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        User user1 =    userService.edit(user);
        return ResponseMessage.success(user1);

    }
    //删除用户
    @DeleteMapping("/{userid}")  //请求方式为delete
    public ResponseMessage delete(@PathVariable  Integer userid)
    {

       userService.delete(userid);
        return ResponseMessage.success(null);

    }
    //查询指定id的用户
    @GetMapping("/detail/{userid}")  //请求方式为Get
    public ResponseMessage get(@PathVariable  Integer userid)
    {
        User user1 =    userService.get(userid);
        return ResponseMessage.success(user1);

    }


    //查询所有用户
    @GetMapping("/list")  // 新增一个路径用于获取分页用户列表
    public ResponseMessage listUsers(@RequestParam(defaultValue = "0") int page,
                                     @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<User> userPage = userService.listUsers(pageable);
        return ResponseMessage.success(userPage);
    }
    //注册用户
    @PostMapping("/register")  //请求方式为Get
    public ResponseMessage register(@Validated  @RequestBody UserDto user)
    {
        if (userService.existsByUserName(user.getUserName()))
        {
            throw new IllegalArgumentException("用户名已经存在！");
        }
        if (userService.existsByUserEmail(user.getUserEmail()))
        {
            //可以预埋一个bug
         //   throw new IllegalArgumentException("邮箱已经存在！");
        }

        User user1 =    userService.add(user);
        return ResponseMessage.success(user1);
    }


    // 登录用户
    @PostMapping("/login")
    public ResponseMessage login(@RequestBody LoginDto loginDto) {
        boolean success = userService.login(loginDto);
        if (success) {
            return ResponseMessage.success("登录成功");
        } else {
            throw new IllegalArgumentException("用户名或密码错误！");
        }
    }

//点击发送验证码。向用户邮箱发送验证码
    @PostMapping("/sendVerificationCode")
    public ResponseMessage sendVerificationCode(@RequestBody EmailRequestDto emailRequest) {
        String email = emailRequest.getEmail();

        if (email == null || email.isEmpty()) {
            throw new IllegalArgumentException("邮箱不能为空！");
        }

        final String FIXED_VERIFICATION_CODE = "8888";

        // 在这里可以添加逻辑来模拟发送邮件（实际上不会真正发送）
        // 真实应用中，你需要将验证码通过邮件服务发送给用户
        // 返回成功响应信息
        return ResponseMessage.success("验证码" + FIXED_VERIFICATION_CODE + "已发送，请查收邮件");
    }


//注册前，先检查验证码是否正确
    @PostMapping("/verifyCode")
    public ResponseMessage verifyCode(@RequestBody EmailRequestDto emailRequest) {
        String verifyCode = emailRequest.getVerifyCode();

        if (!verifyCode.equals("8888")) {
            throw new IllegalArgumentException("验证码错误！");
        }

        return ResponseMessage.success("验证码通过验证");
    }

}
